package com.yingoo.controller;

import com.yingoo.api.HanderRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * Created by lenovo on 2017/7/31.
 */
//@Service
public class MyHanderManager {
    private HashMap<String,Boolean> urlMap =new HashMap();
    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;
    @Autowired
    private DownloadHander downloadHander;
    public void invoke(String seed) {
        urlMap.put(seed, true);
        while (true) {
            int flag = 0;
            List<FutureTask<List<String>>> futureTaskList = new ArrayList();
            for (Map.Entry<String, Boolean> entry : urlMap.entrySet()) {
                if (entry.getValue()) {
                    flag++;
                    HanderRequest handerRequest = new HanderRequest();
                    handerRequest.setUrl(entry.getKey());

                    FutureTask<List<String>> futureTask = new FutureTask<List<String>>(new HanderThread(downloadHander, handerRequest));
                    threadPoolTaskExecutor.execute(futureTask);
                    futureTaskList.add(futureTask);
                    entry.setValue(false);
                }
            }
            if(CollectionUtils.isEmpty(futureTaskList))
                break;
            Iterator<FutureTask<List<String>>> iterable = futureTaskList.iterator();
            while (iterable.hasNext()){
                FutureTask<List<String>> futureTask = iterable.next();
                if (futureTask.isDone()) {
                    try {
                        List<String> urlList = futureTask.get();
                        if (!CollectionUtils.isEmpty(urlList)) {
                            for (String url : urlList) {
                                if(!urlMap.containsKey(url))
                                    urlMap.put(url, true);
                            }
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (ExecutionException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    @Scheduled(fixedDelay = 2345*1000)
    public void Task(){
        System.out.println("start");
        invoke("https://www.baidu.com");
    }
}
